import datetime
import xml.etree.ElementTree as ET
from utils.xml_utils import pretty_xml

def create_template_kml_content(geojson_polygon_coords, flight_params):
    """
    根据GeoJSON坐标和飞行参数生成 template.kml 的内容 (XML字符串)
    """
    # 注册命名空间以便ElementTree正确处理带前缀的标签
    ET.register_namespace('', "http://www.opengis.net/kml/2.2")
    ET.register_namespace('wpml', "http://www.dji.com/wpmz/1.0.6")

    # 根元素
    kml_element = ET.Element("{http://www.opengis.net/kml/2.2}kml")
    document_element = ET.SubElement(kml_element, "{http://www.opengis.net/kml/2.2}Document")

    # 添加 <name> 标签来指定航线名称
    ET.SubElement(document_element, "{http://www.opengis.net/kml/2.2}name").text = flight_params['route_name']

    # 基本信息
    ET.SubElement(document_element, "{http://www.dji.com/wpmz/1.0.6}author").text = flight_params['author']
    ET.SubElement(document_element, "{http://www.dji.com/wpmz/1.0.6}createTime").text = str(int(datetime.datetime.now().timestamp() * 1000))
    ET.SubElement(document_element, "{http://www.dji.com/wpmz/1.0.6}updateTime").text = str(int(datetime.datetime.now().timestamp() * 1000))

    # missionConfig
    mission_config = ET.SubElement(document_element, "{http://www.dji.com/wpmz/1.0.6}missionConfig")
    ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}flyToWaylineMode").text = "safely"
    ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}finishAction").text = "goHome"
    ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}exitOnRCLost").text = "goContinue"
    ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}executeRCLostAction").text = "goBack"
    ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}takeOffSecurityHeight").text = str(flight_params['takeoff_security_height'])
    
    if geojson_polygon_coords: # 使用第一个点作为起飞参考点
        takeoff_ref_point_str = f"{geojson_polygon_coords[0][1]},{geojson_polygon_coords[0][0]},{flight_params.get('takeoff_ref_point_alt', 30.0)}" # lat,lon,alt
        ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}takeOffRefPoint").text = takeoff_ref_point_str
        ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}takeOffRefPointAGLHeight").text = str(8.0) # 使用飞行高度作为AGL

    ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}globalTransitionalSpeed").text = str(flight_params['speed'])
    ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}globalRTHHeight").text = "100" # 与样本一致或可配置

    drone_info = ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}droneInfo")
    ET.SubElement(drone_info, "{http://www.dji.com/wpmz/1.0.6}droneEnumValue").text = flight_params['drone_enum']
    ET.SubElement(drone_info, "{http://www.dji.com/wpmz/1.0.6}droneSubEnumValue").text = flight_params['drone_sub_enum']

    auto_eroute_info = ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}autoErouteInfo")
    ET.SubElement(auto_eroute_info, "{http://www.dji.com/wpmz/1.0.6}transitionalAutoRerouteMode").text = "1"
    ET.SubElement(auto_eroute_info, "{http://www.dji.com/wpmz/1.0.6}missionAutoRerouteMode").text = "1"
    
    ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}waylineAvoidLimitAreaMode").text = "0"

    payload_info = ET.SubElement(mission_config, "{http://www.dji.com/wpmz/1.0.6}payloadInfo")
    ET.SubElement(payload_info, "{http://www.dji.com/wpmz/1.0.6}payloadEnumValue").text = flight_params['payload_enum']
    ET.SubElement(payload_info, "{http://www.dji.com/wpmz/1.0.6}payloadSubEnumValue").text = flight_params['payload_sub_enum']
    ET.SubElement(payload_info, "{http://www.dji.com/wpmz/1.0.6}payloadPositionIndex").text = "0"

    # Folder
    folder_element = ET.SubElement(document_element, "{http://www.opengis.net/kml/2.2}Folder")
    ET.SubElement(folder_element, "{http://www.dji.com/wpmz/1.0.6}templateType").text = "mapping2d" # 与样本一致
    ET.SubElement(folder_element, "{http://www.dji.com/wpmz/1.0.6}templateId").text = "0"
    
    # 添加 <wpml:mappingMode> 和 <wpml:routeOptimizationMode>
    ET.SubElement(folder_element, "{http://www.dji.com/wpmz/1.0.6}mappingMode").text = "1"
    ET.SubElement(folder_element, "{http://www.dji.com/wpmz/1.0.6}routeOptimizationMode").text = "1"
    
    coord_sys_param = ET.SubElement(folder_element, "{http://www.dji.com/wpmz/1.0.6}waylineCoordinateSysParam")
    ET.SubElement(coord_sys_param, "{http://www.dji.com/wpmz/1.0.6}coordinateMode").text = "WGS84"
    ET.SubElement(coord_sys_param, "{http://www.dji.com/wpmz/1.0.6}heightMode").text = "EGM96" # 与样本一致
    ET.SubElement(coord_sys_param, "{http://www.dji.com/wpmz/1.0.6}globalShootHeight").text = str(flight_params['altitude'])

    ET.SubElement(folder_element, "{http://www.dji.com/wpmz/1.0.6}autoFlightSpeed").text = str(flight_params['speed'])

    # Placemark for the polygon area
    placemark_element = ET.SubElement(folder_element, "{http://www.opengis.net/kml/2.2}Placemark")
    
    # 添加缺失的静态wpml参数 (与大疆样本一致)
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}caliFlightEnable").text = "0"
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}elevationOptimizeEnable").text = "0"
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}smartObliqueEnable").text = "0"
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}quickOrthoMappingEnable").text = "0"
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}facadeWaylineEnable").text = "0"
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}isLookAtSceneSet").text = "0"
    
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}shootType").text = flight_params.get('shoot_type', 'time')
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}direction").text = str(flight_params.get('direction', '11'))
    
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}margin").text = "0"
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}efficiencyFlightModeEnable").text = "0"

    # 添加 <wpml:overlap> 结构
    overlap_element = ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}overlap")
    ET.SubElement(overlap_element, "{http://www.dji.com/wpmz/1.0.6}orthoCameraOverlapH").text = str(flight_params.get('ortho_camera_overlap_h', 70))
    ET.SubElement(overlap_element, "{http://www.dji.com/wpmz/1.0.6}orthoCameraOverlapW").text = str(flight_params.get('ortho_camera_overlap_w', 60))
    ET.SubElement(overlap_element, "{http://www.dji.com/wpmz/1.0.6}inclinedCameraOverlapH").text = "0" # 根据样本，通常为0，或后续可配置
    ET.SubElement(overlap_element, "{http://www.dji.com/wpmz/1.0.6}inclinedCameraOverlapW").text = "0" # 根据样本，通常为0，或后续可配置

    polygon_element = ET.SubElement(placemark_element, "{http://www.opengis.net/kml/2.2}Polygon")
    outer_boundary_is = ET.SubElement(polygon_element, "{http://www.opengis.net/kml/2.2}outerBoundaryIs")
    linear_ring = ET.SubElement(outer_boundary_is, "{http://www.opengis.net/kml/2.2}LinearRing")
    
    # 转换GeoJSON坐标为KML格式 (lon,lat,alt)
    # GeoJSON: [lon, lat] or [lon, lat, alt]
    # KML coordinates: lon,lat,alt lon,lat,alt ...
    kml_coords_str = " ".join([f"{coord[0]},{coord[1]},{coord[2] if len(coord) > 2 else 0}" for coord in geojson_polygon_coords])
    ET.SubElement(linear_ring, "{http://www.opengis.net/kml/2.2}coordinates").text = kml_coords_str

    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}ellipsoidHeight").text = str(flight_params['altitude'])
    ET.SubElement(placemark_element, "{http://www.dji.com/wpmz/1.0.6}height").text = str(flight_params['altitude'] - flight_params.get('egm96_offset', 7.3)) # 假设一个EGM96偏移，或用户提供

    # payloadParam
    payload_param = ET.SubElement(folder_element, "{http://www.dji.com/wpmz/1.0.6}payloadParam")
    ET.SubElement(payload_param, "{http://www.dji.com/wpmz/1.0.6}payloadPositionIndex").text = "0"
    ET.SubElement(payload_param, "{http://www.dji.com/wpmz/1.0.6}focusMode").text = "firstPoint"
    # 添加 <wpml:imageFormat>
    ET.SubElement(payload_param, "{http://www.dji.com/wpmz/1.0.6}imageFormat").text = flight_params.get('image_format', 'JPG')

    return pretty_xml(kml_element) # 使用美化输出进行调试